package com.regulaforensics.date_reminder;

import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class PreferencesActivity extends Activity{
	
	private Spinner spinner;
	private Spinner spinnerOut;
	private CheckBox checkBox;
	private CheckBox checkBoxVibra;
	private TextView alarmTime;
	private int alarmHour;
	private int alarmMinute;
	private int checkVibra;
	static final int TIME_DIALOG_ID = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.pref);
		
		spinner = (Spinner) findViewById(R.id.type_spinner);
	    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
	            this, R.array.type_array, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner.setAdapter(adapter);
	    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
	    
	    spinnerOut = (Spinner) findViewById(R.id.output_spinner);
	    ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
	            this, R.array.out_array, android.R.layout.simple_spinner_item);
	    adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinnerOut.setAdapter(adapter2);
	    spinnerOut.setOnItemSelectedListener(new MyOnItemSelectedListenerOut());
	    
	    
	    checkBox = (CheckBox) findViewById(R.id.service_checkbox);
	    checkBoxVibra = (CheckBox) findViewById(R.id.vibration_checkbox);
	   
	    alarmTime = (TextView)findViewById(R.id.alarm_time);
	   
	    SharedPreferences settings = getSharedPreferences(DateReminderActivity.PREFS_NAME, 0);
	    int alarmOnOff = settings.getInt(DateReminderActivity.ALARMONOFF, 1);
	    if(alarmOnOff==0)
	    	checkBox.setChecked(false);
	    else
	    	checkBox.setChecked(true);
	    
	    
	   ////checkbox listener
	   checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			SharedPreferences settings = getSharedPreferences(DateReminderActivity.PREFS_NAME, 0);
			SharedPreferences.Editor editor = settings.edit();
			if(isChecked){
		        editor.putInt(DateReminderActivity.ALARMONOFF, 1);
		        // Commit the edits!
		        editor.commit();
			}
			else{
		        editor.putInt(DateReminderActivity.ALARMONOFF, 0);
		        // Commit the edits!
		        editor.commit();
			}
				
			
		}
		});
	   
	   ///checkboxVibra
	   checkBoxVibra.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				SharedPreferences settings = getSharedPreferences(DateReminderActivity.PREFS_NAME, 0);
		        SharedPreferences.Editor editor = settings.edit();
				if(isChecked){
			        editor.putInt(DateReminderActivity.VIBRATE, 1);
			        // Commit the edits!
			        editor.commit();
				}
				else{
			        editor.putInt(DateReminderActivity.VIBRATE, 0);
			        // Commit the edits!
			        editor.commit();
				}
					
				
			}
			});
	}

	@Override
	protected void onPause() {
		super.onPause();
		try{
			SharedPreferences settings = getSharedPreferences(DateReminderActivity.PREFS_NAME, 0);
	        SharedPreferences.Editor editor = settings.edit();
	        editor.putInt(DateReminderActivity.TYPE_NAME, (int)spinner.getSelectedItemId());
	        editor.putInt(DateReminderActivity.OUTPUT_NAME, (int)spinnerOut.getSelectedItemId());
	        // Commit the edits!
	        editor.commit();
		}
		catch (Exception e) {
			Context context = getApplicationContext();  
    	    CharSequence text = e.toString();  
    	    int duration = Toast.LENGTH_LONG;  
    	    Toast toast = Toast.makeText(context, text, duration);  
    	    toast.show(); 
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		try{
			SharedPreferences settings = getSharedPreferences(DateReminderActivity.PREFS_NAME, 0);
			spinner.setSelection(settings.getInt(DateReminderActivity.TYPE_NAME, DateReminderActivity.DAY_TYPE));
			spinnerOut.setSelection(settings.getInt(DateReminderActivity.OUTPUT_NAME, DateReminderActivity.OUT_YEAR));
			alarmHour = settings.getInt(DateReminderActivity.ALARM_HOUR, 7);
			alarmMinute = settings.getInt(DateReminderActivity.ALARM_MINUTE, 0);
			
			checkVibra =  settings.getInt(DateReminderActivity.VIBRATE, 0);
			if(checkVibra==1)
				checkBoxVibra.setChecked(true);
			else
				checkBoxVibra.setChecked(false);
			
			updateTimeDisplay();
		}
		catch (Exception e) {
			Context context = getApplicationContext();  
    	    CharSequence text = e.toString();  
    	    int duration = Toast.LENGTH_LONG;  
    	    Toast toast = Toast.makeText(context, text, duration);  
    	    toast.show(); 
		}
	}
	
	
//	private boolean isMyServiceRunning() {
//		boolean serRun=false;
//	    
//		SharedPreferences settings = getSharedPreferences(DateReminderActivity.PREFS_NAME, 0);
//		int service_running = settings.getInt(DateReminderActivity.SERVICE_RUNNING, 0);
//		
//		if(service_running==1)
//			serRun = true;
//		
////		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
////	    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
////	    	
////	        if ("com.regulaforensics.date_reminder.ReminderService".equals(service.service.getClassName())) {
////	            serRun = true;
////	            break;
////	        }
////	    }
//	    return serRun;
//	}
	

	public class MyOnItemSelectedListener implements OnItemSelectedListener {
		
	    public void onItemSelected(AdapterView<?> parent,
	        View view, int pos, long id) {
	    	
	    	// We need an Editor object to make preference changes.
	        // All objects are from android.context.Context
	        SharedPreferences settings = getSharedPreferences(DateReminderActivity.PREFS_NAME, 0);
	        SharedPreferences.Editor editor = settings.edit();
	        editor.putInt(DateReminderActivity.TYPE_NAME, (int) id);
	        // Commit the edits!
	        editor.commit();
	        
	    }

	    public void onNothingSelected(AdapterView<?> parent) {
	      // Do nothing.
	    }
	}
	
	public class MyOnItemSelectedListenerOut implements OnItemSelectedListener {
		
	    public void onItemSelected(AdapterView<?> parent,
	        View view, int pos, long id) {
	    	
	    	// We need an Editor object to make preference changes.
	        // All objects are from android.context.Context
	        SharedPreferences settings = getSharedPreferences(DateReminderActivity.PREFS_NAME, 0);
	        SharedPreferences.Editor editor = settings.edit();
	        editor.putInt(DateReminderActivity.OUTPUT_NAME, (int) id);
	        // Commit the edits!
	        editor.commit();
	    }

	    public void onNothingSelected(AdapterView<?> parent) {
	      // Do nothing.
	    }
	}
	
	
	public void clickFun(View v){
		
		switch (v.getId()) 
		{
		    case R.id.alarm_time:
		    	showDialog(TIME_DIALOG_ID);
		        break;
	    }
	}
	
	 @Override
	    protected Dialog onCreateDialog(int id) {
	        switch (id) {
	        case TIME_DIALOG_ID:
	            return new TimePickerDialog(this,
	            			mTimeSetListener,
	                        alarmHour, alarmMinute, true);
	        }
	        return null;
	    }
	 
	 // the callback received when the user "sets" the date in the dialog
	    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
	            new TimePickerDialog.OnTimeSetListener() {

	                public void onTimeSet(TimePicker view, int getHour, 
	                                      int getMinute) {
	                	if((getHour!=alarmHour) || (getMinute!=alarmMinute)){ //set new alarm time
	            	        
	                		SharedPreferences settings = getSharedPreferences(DateReminderActivity.PREFS_NAME, 0);
	            	        SharedPreferences.Editor editor = settings.edit();
	            	        editor.putInt(DateReminderActivity.ALARM_HOUR, getHour);
	            	        editor.putInt(DateReminderActivity.ALARM_MINUTE, getMinute);
	            	        // Commit the edits!
	            	        editor.commit();
	            	        
	            	        alarmHour = getHour;
	            	        alarmMinute = getMinute;
	            	        
	            	        updateTimeDisplay();
	            	        
	            	        Context context = getApplicationContext(); 
	            	        //stopService(new Intent(context,ReminderService.class));
	            	        ///and run it
	            			Intent myintent = new Intent(context, ReminderService.class);
	            			myintent.putExtra(ReminderService.RERUN, 1);
	            			startService(myintent);
	            	        
	                	}
	                }
	            };
	            
	 // updates the date in the TextView
	            private void updateTimeDisplay() {
	            	
	            	String hourZero = "";
	            	String minuteZero = "";
	            	if(alarmHour<10)
	            		hourZero = "0";
	            	if(alarmMinute<10)
	            		minuteZero = "0";
	            	
	            	alarmTime.setText(
	                    new StringBuilder()
	                            // construct alarm time
	                            .append(hourZero)
	                    		.append(alarmHour).append(":")
	                    		.append(minuteZero)
	                            .append(alarmMinute).append(""));
	            }
	
}
